/*
 * Copyright (c) 2018-2999 北京小象智慧信息科技有限公司 All rights reserved.
 *
 * https://www.xiaoxiangai.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yami.shop.api.utils.HttpResult;
import com.yami.shop.bean.model.*;
import com.yami.shop.dao.MemberMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.service.impl.SendMessageToUserServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;


@RestController
@RequestMapping("/notice/pay")
public class PayNoticeController {

    /**
     * 小程序支付
     */
    @Autowired
    private  WxPayService wxMiniPayService;
    @Autowired
    private  PayService payService;
    @Autowired
    private  OrderSettlementService orderSettlementService;
    @Autowired
    private  OrderService orderService;
    @Autowired
    private  OrderItemService orderItemService;
    @Autowired
    private  RebateRecordsService rebateRecordsService;
    @Autowired
    private  UserService userService;
    @Autowired
    private   MemberService memberService;
    @Autowired
    private SendMessageToUserServiceImpl sendMessageToUserService;
    @Autowired
    private SmsLogService smsLogService;
    @Autowired
    private ShopDetailService shopDetailService;


    @RequestMapping("/order")
    public ResponseEntity<Void> submit(@RequestBody String xmlData) throws WxPayException {
        WxPayOrderNotifyResult parseOrderNotifyResult = wxMiniPayService.parseOrderNotifyResult(xmlData);
        String payNo = parseOrderNotifyResult.getOutTradeNo();
        String bizPayNo = parseOrderNotifyResult.getTransactionId();
        //根据支付的订单编号,查询当前的订单状态，只有当状态为1的时候，才允许更新订单的内部状态
        OrderSettlement orderSettlement = orderSettlementService.getSettlementByPayNo(payNo);
        String userId  = orderSettlement.getUserId();
        User user = userService.getUserByUserId(userId);
        String puserId = null;
        if(user!=null){
            puserId  = user.getPuserid();
        }
        if(orderSettlement!=null){
            String orderNumber =  orderSettlement.getOrderNumber();
            if(null!=orderNumber&&!"".equals(orderNumber)){
                    Order order = orderService.getOrderByOrderNumber(orderNumber);
                    Long shopId = order.getShopId();
                    ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
                    //获取管理员的电话
                    ShopDetail adminShopDetail = shopDetailService.getShopDetailByShopId(1L);
                    String adminMobile = null;
                    if(adminShopDetail!=null){
                        adminMobile = adminShopDetail.getMobile();
                    }
                    if(order!=null){
                        Integer status = order.getStatus();
                        Long orderId =  order.getOrderId();
                        //支付状态
                        int payStatus = orderSettlement.getPayStatus();
                        if(status==1){
                            //对支付成功的订单进行处理
                            orderService.dealOrderSuccess(order,payNo,bizPayNo,orderNumber,puserId);
                            //推送消息模板
                            this.sendMessage(order,orderSettlement);
                            //如果订单是用户自提,不用推送订单给美团
                            try {
                                if(order.getDistributionType()!=1&&shopDetail.getMeituanDistributionFlag()==1) {
                                    orderService.pushOrderToMeiTuan(order);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            //短信通知商家
                            if(null!=shopDetail) {
                                smsLogService.sendSmsToShop(shopDetail.getShopName(), shopDetail.getMobile(),order.getOrderNumber(),adminMobile);
                            }
                            // sendMessageToUserService.pushWxAdmin(order,orderSettlement);
                        }
                    }
            }
        }



        return ResponseEntity.ok().build();
    }

    @PostMapping("/callback")
    public ResponseEntity<String> callback(PayResult payResult) throws WxPayException {
        String payNo = payResult.getTargetOrderId();
        String bizPayNo = null;
        //根据支付的订单编号,查询当前的订单状态，只有当状态为1的时候，才允许更新订单的内部状态
        String merOrderId = payResult.getMerOrderId();
        String merOrderNumber = null;
        if(merOrderId!=null&&!"".equals(merOrderId)){
            String[] merOrderIds =  merOrderId.split("30AQ");
            merOrderNumber = merOrderIds[1];
        }
        OrderSettlement orderSettlement = orderSettlementService.getSettlementByOrderNumber(merOrderNumber);
        String userId  = orderSettlement.getUserId();
        User user = userService.getUserByUserId(userId);
        String puserId = null;
        if(user!=null){
            puserId  = user.getPuserid();
        }
        if(orderSettlement!=null){
            String orderNumber =  orderSettlement.getOrderNumber();
            if(null!=orderNumber&&!"".equals(orderNumber)){
                Order order = orderService.getOrderByOrderNumber(orderNumber);
                Long shopId = order.getShopId();
                ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
                //获取管理员的电话
                ShopDetail adminShopDetail = shopDetailService.getShopDetailByShopId(1L);
                String adminMobile = null;
                if(adminShopDetail!=null){
                    adminMobile = adminShopDetail.getMobile();
                }
                if(order!=null){
                    Integer status = order.getStatus();
                    Long orderId =  order.getOrderId();
                    //支付状态
                    String payStatus = payResult.getStatus();
                    if(status==1&&!"".equals(payStatus)&&payStatus!=null&&payStatus.equals("TRADE_SUCCESS")){
                        //对支付成功的订单进行处理
                        orderService.dealOrderSuccess(order,payNo,bizPayNo,orderNumber,puserId);
                        //推送消息模板
                        this.sendMessage(order,orderSettlement);
                        //如果订单是用户自提,不用推送订单给美团
                        try {
                            if(order.getDistributionType()!=1&&shopDetail.getMeituanDistributionFlag()==1) {
                                orderService.pushOrderToMeiTuan(order);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //短信通知商家
                        if(null!=shopDetail) {
                            smsLogService.sendSmsToShop(shopDetail.getShopName(), shopDetail.getMobile(),order.getOrderNumber(),adminMobile);
                        }
                        // sendMessageToUserService.pushWxAdmin(order,orderSettlement);
                    }
                }
            }
        }
        return ResponseEntity.ok("SUCCESS");
    }

    /**
     * 线上充值金额回调,确认充值金额成功入账
     */
    @PostMapping("/depositMoneySuccess")
    public HttpResult depositMoneySuccess(PayResult payResult){

        return  HttpResult.success();
    }



    @RequestMapping("sendMessage")
    public void sendMessage(Order order,OrderSettlement orderSettlement){
        sendMessageToUserService.pushWxAdmin(order,orderSettlement);
    }

    @PostMapping("/pushOrderTomeituan")
    public void pushOrderTomeituan(String orderNumber){
        Order order = orderService.getOrderByOrderNumber(orderNumber);
        try {
            if(order.getDistributionType()!=1) {
                orderService.pushOrderToMeiTuan(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/dealRebate")
    public void dealRebate(){
        Order order  = orderService.getOrderByOrderNumber("1306396491157475328");
        String payNo = "1306396496299692032";
        String bizPayNo = "";
        String orderNumber = "1306396491157475328";
        String puserId = "33b9fa279e23408990c7c320df0c32cf";
        orderService.dealOrderSuccess(order,payNo,bizPayNo,orderNumber,puserId);
    }

    @PostMapping("/testUser")
    public void getUser(){
        String payNo = "1306396496299692032";
        OrderSettlement orderSettlement = orderSettlementService.getSettlementByPayNo(payNo);
        String userId  = orderSettlement.getUserId();
        User user = userService.getUserByUserId(userId);
        String puserId = null;
        if(user!=null){
            puserId  = user.getPuserid();
        }

    }


}
